import puppeteer, { Page } from 'puppeteer';
import { getUserAgent } from '../utils/crawlerUtils';
import fs from 'fs';
import path from 'path';
import { app } from 'electron';
import SpyConfig from './config';

const RESOURCES_PATH = app.isPackaged
    ? path.join(process.resourcesPath, '')
    : path.join(__dirname, '../../');

let stealthPath = path.join(RESOURCES_PATH, '/assets/stealth.min.js');

class SpyHelper {
    _userAgent: string;
    _page: Page | undefined;
    private config: SpyConfig;
    constructor(config: SpyConfig) {
        this._userAgent = getUserAgent();
        this.config = config;
    }
    async init(ip?: string){
        let options: any = {
            headless: true,
            executablePath: this.config.getProp('chrome_path'),
        };

        if (ip) {
            options.args = [
                `--proxy-server=${ip}`
            ]
        }
        // const browser = await puppeteer.launch({headless: false});
        const browser = await puppeteer.launch(options);
        const page = await browser.newPage();
        this._page = page;
        await page.setUserAgent(this._userAgent);
        await page.setViewport({width: 1366, height: 768});
    }
    async getQrCode(): Promise<string> {
        if (this._page) {
            const page = this._page;
            await page.goto('https://www.kuaishou.com/thirdPart/wechat');
            await page.addScriptTag({ 'path': stealthPath });
            await page.waitForSelector('.web_qrcode_img');
            const imageList:string [] = await page.$$eval('img.web_qrcode_img', images => images.map(img => img.src));
            // 广播通知
            const qrCode = imageList[0] || '';
            return qrCode;
        }

        return '';
    }

    async saveCookie() {
        if (this._page) {
            await this._page.waitForSelector('.main-content', {timeout: 3 * 60 * 1000});
            await this._page.goto('https://id.kuaishou.com/');
            const cookies = await this._page.cookies();
            const user = cookies.find(item => item.name === 'userId');
            const passToken = cookies.find(item => item.name === 'passToken');
            const dir = `${RESOURCES_PATH}/userData`;

            if (!fs.existsSync(dir)){
                fs.mkdirSync(dir);
            }
            if (user) {
                fs.writeFileSync(`${RESOURCES_PATH}/userData/${user.value}`, passToken?.value + '');
            }
        }
    }
}

const closeVerify = async (page: Page) => {
    const frameHandle = await page.$('iframe'); // 获取iframe元素的句柄
    if (frameHandle) {
        const frame = await frameHandle.contentFrame();
        // 如果有安全验证  进行关闭
        if (frame) {
            await frame.waitForSelector('.icon-close');
            await frame.click('.icon-close');
            await page.waitForFunction(() => !document.querySelector('iframe'));
        }
    }
};

export default SpyHelper;